package com.tledu.dangjian.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.StringUtils;
import com.tledu.dangjian.core.AjaxResult;
import com.tledu.dangjian.core.annotion.Auth;
import com.tledu.dangjian.core.constants.CommonConstants;
import com.tledu.dangjian.core.constants.ErrorCodeConstants;
import com.tledu.dangjian.core.exception.UsernameRepeatException;
import com.tledu.dangjian.model.Role;
import com.tledu.dangjian.model.User;
import com.tledu.dangjian.service.IRoleService;
import com.tledu.dangjian.service.IUserService;
import com.tledu.dangjian.service.impl.UserServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cyrus
 */
@Controller
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {

    private IUserService userService;

    private IRoleService roleService;

    @GetMapping("/list")
    @Auth(auth = "user")
    public String userList(User user, @RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize, Model model) {
        PageHelper.startPage(pageNum, pageSize);
        model.addAttribute("pageInfo", PageInfo.of(userService.list(user)));
        return "user/list";
    }

    @PostMapping("/list")
    @ResponseBody
    public PageInfo list(User user, @RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize, Model model) {
        PageHelper.startPage(pageNum, pageSize);
        return PageInfo.of(userService.list(user));
    }

    @GetMapping("/add")
    public String add(Model model) {
        // 把所有的角色列出来
        model.addAttribute("allRoles", roleService.list(new Role()));
        return "user/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addActions(@RequestBody User user) {
        userService.insert(user);
        return new AjaxResult("保存成功", null);
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable Integer id) {
        userService.delete(id);
        return new AjaxResult("删除成功", null);
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        User user = userService.selectById(id);
        model.addAttribute("entity", user);
        // 跳转到编辑界面的时候需要全部的角色
        List<Integer> selectedRoleIdList = new ArrayList<>();
        for (Role role : user.getRoleList()) {
            selectedRoleIdList.add(role.getRoleId());
        }
        model.addAttribute("selectedRoleIdList", selectedRoleIdList);
        model.addAttribute("allRoles", roleService.list(new Role()));
        return "user/edit";
    }

    @PutMapping("/edit")
    @ResponseBody
    public AjaxResult edit(@RequestBody User user) {
        userService.update(user);
        return new AjaxResult("修改成功", null);
    }

    @ExceptionHandler(value = UsernameRepeatException.class)
    @ResponseBody
    public AjaxResult handleException(UsernameRepeatException e) {
        return new AjaxResult(e.getMessage(), ErrorCodeConstants.USERNAME_REPEAT, null);
    }

    @GetMapping("/personal-center")
    public String personalCenter(HttpSession session,Model model) {
        User user = (User) session.getAttribute(CommonConstants.LOGIN_USER_SESSION_KEY);
        model.addAttribute("user", user);
        return "user/personal-center";
    }

    @PostMapping("/upload/avatar")
    @ResponseBody
    public AjaxResult<User> avatarUpload(MultipartFile file, HttpSession session, Model model) {
        User user = (User) session.getAttribute(CommonConstants.LOGIN_USER_SESSION_KEY);
        // 把头像保存起来
        if (file.isEmpty()) {
            return new AjaxResult<>("请选择文件",ErrorCodeConstants.PARAMETER_ERROR,null);
        }

        // 需要把文件保存起来
        String savePath = file.getOriginalFilename();
        File saveFile = new File(CommonConstants.FILE_UPLOAD_LOCATION + File.separator + savePath);
        try {
            file.transferTo(saveFile);
            // 保存用户头像
            user.setAvatar("/file/"+savePath);
            userService.update(user);
            session.setAttribute(CommonConstants.LOGIN_USER_SESSION_KEY,user);
            return new AjaxResult<>("上传成功",user);
        } catch (IOException e) {
            return new AjaxResult<>("文件上传失败",ErrorCodeConstants.BUSINESS_EXCEPTION,null);
        }

    }

}
